//
//  BCEditorTextView.m
//  图片编辑
//
//  Created by aaaa on 2020/3/31.
//  Copyright © 2020 aaaa. All rights reserved.
//

#import "BCEditorTextView.h"
#import "BCColorBoard.h"

static const CGFloat bottom_margin = 15;

@interface BCEditorTextView()<UITextViewDelegate>

@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) __block UIColor *textColor;
@property (nonatomic, strong) UILabel *charNumLabel;
@property (nonatomic, strong) UIButton *colorBoardBtn;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UIButton *finishBtn;
@property(nonatomic,strong) BCColorBoard *colorBoard;
@end

@implementation BCEditorTextView

-(instancetype)initWithFrame:(CGRect)frame
                        text:(NSString *)text
                   textColor:(UIColor *)textColor{
    if (self = [super initWithFrame:frame]) {
        _textColor = textColor;
        self.textView.text = text;
        [self textViewDidChange:_textView];
        //监听键盘frame改变
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [self initUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _textColor = [UIColor whiteColor];
        //监听键盘frame改变
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [self initUI];
    }
    return self;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



-(void)initUI{
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];    
    _colorBoard = [BCColorBoard new];
    __weak typeof(self) weakself = self;
    _colorBoard.didselectColor = ^(UIColor * _Nonnull color) {
        weakself.textView.textColor = color;
    };
    [self addSubview:_colorBoard];
    
    [self addSubview:self.backBtn];
    [self addSubview:self.finishBtn];
    [self addSubview:self.textView];
    [self addSubview:self.charNumLabel];
    [self addSubview:self.colorBoardBtn];
    
    self.charNumLabel.left = 15;
    self.colorBoardBtn.right = ScreenW - 15;
    self.finishBtn.right = self.colorBoardBtn.right;
    
    if (@available(iOS 11, *)) {
        self.charNumLabel.bottom = self.colorBoardBtn.bottom = ScreenH - bottom_margin - self.safeAreaInsets.bottom;
    } else {
        self.charNumLabel.bottom = self.colorBoardBtn.bottom = ScreenH - bottom_margin;
    }
    
    [self.textView becomeFirstResponder];
}

#pragma mark - delegate -
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    NSUInteger old_length = [self unicodeLengthWithText:self.textView.text];
    NSUInteger new_length = [self unicodeLengthWithText:text];
    NSUInteger total_length = old_length + new_length;
    
    if (total_length > 50) return NO;

    self.charNumLabel.text = [NSString stringWithFormat:@"%lu/50",total_length];
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView{
    self.finishBtn.enabled = textView.text.length > 0;
    CGSize size = [textView sizeThatFits:CGSizeMake(ScreenW- 30*2, MAXFLOAT)];
    textView.size = size;
}

#pragma mark - user interaction -
-(void)showColorBoard:(UIButton *)btn{
    if ([_colorBoard isShowing]) {
        [_colorBoard disappear];
    }else{
        [_colorBoard showAtPosition:btn.origin];
    }
}

-(void)finish{
    !_didInputText?:_didInputText(_textView.size,_textView.text,_textView.textColor);
    [self dismiss];
}

-(void)dismiss{
    self.userInteractionEnabled = NO;
    [self resignFirstResponder];
    [self removeFromSuperview];
}

#pragma mark -  -
-(NSUInteger) unicodeLengthWithText:(NSString *)text{
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < text.length; i++) {
        unichar uc = [text characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    return asciiLength;
}

#pragma mark - keyboard -
//键盘即将弹出
- (void)keyboardWillShow:(NSNotification *)notification {
    //获取键盘高度 keyboardHeight
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    NSLog(@" %s - %f",__func__,keyboardRect.size.height);
    
    _colorBoardBtn.bottom = ScreenH - keyboardRect.size.height - bottom_margin;
    _charNumLabel.bottom  = _colorBoardBtn.bottom;
}

#pragma mark - getter -
- (UITextView *)textView {
    if (!_textView) {
        _textView = [[UITextView alloc] initWithFrame:CGRectMake(30, 100, 0, 150)];
        _textView.backgroundColor = [UIColor clearColor];
        _textView.font = [UIFont systemFontOfSize:25];
        _textView.tintColor = RGB_COLOR(56, 172, 255);
        _textView.textColor = _textColor ? _textColor : [UIColor whiteColor];
        _textView.scrollEnabled = NO;
        _textView.delegate = self;
        _textView.clipsToBounds = NO;
        _textView.keyboardAppearance = UIKeyboardAppearanceDark;
    }
    return _textView;
}

-(UILabel *)charNumLabel{
    if (!_charNumLabel) {
        _charNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,50,15)];
        _charNumLabel.font = [UIFont systemFontOfSize:14.0];
        _charNumLabel.textColor = [UIColor whiteColor];
        _charNumLabel.text = @"0/50";
    }
    return _charNumLabel;
}


-(UIButton *)colorBoardBtn{
    if (!_colorBoardBtn) {
        _colorBoardBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _colorBoardBtn.frame = CGRectMake(0, 0, 40, 40);
        [_colorBoardBtn setImage:[UIImage imageNamed:@"img_colorBoard_default"] forState:UIControlStateNormal];
        [_colorBoardBtn setImage:[UIImage imageNamed:@"img_colorBoard_select"] forState:UIControlStateHighlighted];
        [_colorBoardBtn addTarget:self action:@selector(showColorBoard:) forControlEvents:UIControlEventTouchUpInside];
        _colorBoardBtn.tintColor = _textColor;
    }
    return _colorBoardBtn;
}

-(UIButton *)backBtn{
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _backBtn.frame = CGRectMake(10, 20, 50, 50);
        [_backBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
        [_backBtn setImage:[UIImage imageNamed:@"img_backward_enable"] forState:UIControlStateNormal];
    }
    return _backBtn;
}

-(UIButton *)finishBtn{
    if (!_finishBtn) {
        _finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _finishBtn.frame = CGRectMake(10, 20, 50, 50);
        [_finishBtn addTarget:self action:@selector(finish) forControlEvents:UIControlEventTouchUpInside];
        [_finishBtn setTitle:@"完成" forState:UIControlStateNormal];
        _finishBtn.enabled = NO;
    }
    return _finishBtn;
}
@end
